/***************************************************************************
 *   Copyright (C) 2008/2009 by Philipp Müller <philipp.mueller@gmx.de>    *
 *   Copyright (C) 2008 by Tanguy Krotoff <tkrotoff@gmail.com>             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA          *
 ***************************************************************************/

#include <QHeaderView>

#include "qtvomp.h"
#include "widgetosdtv.h"

WidgetOsdTv::WidgetOsdTv( MainWindow * mainWindow, QWidget *parent ) : QWidget( parent ),
    m_mainWindow( mainWindow ),
    m_index()
{
    setAutoFillBackground ( true );
    setBackgroundRole( QPalette::Light );

    ui.setupUi( this );

    ui.tableWidget->horizontalHeader()->setStretchLastSection( true );
    ui.tableWidget->horizontalHeader()->setResizeMode( 0, QHeaderView::ResizeToContents );
    ui.tableWidget->horizontalHeader()->setVisible( false );
    ui.tableWidget->verticalHeader()->setVisible( false );
    ui.tableWidget->verticalHeader()->setResizeMode( QHeaderView::ResizeToContents );

    //Let's show 2 rows max
    ui.tableWidget->setMaximumHeight( ui.tableWidget->verticalHeader()->sectionSizeHint( 0 ) * 2 );

    m_mapper = new QDataWidgetMapper( this );
    m_mapper->setModel( m_mainWindow->channelListModel() );

    m_mapper->addMapping( ui.channelName,   ChannelListModel::ChannelName, "text" );
    m_mapper->addMapping( ui.channelNumber, ChannelListModel::ChannelNumber, "text" );
    m_mapper->addMapping( ui.icon,          ChannelListModel::ChannelIcon, "pixmap" );

    connect( mainWindow->channelListModel(),  SIGNAL( epgListChanged( int ) ),
             this,                            SLOT( updateEpgList( int ) ) );
    connect( m_mapper,  SIGNAL( currentIndexChanged( int ) ),
             this,      SLOT( updateEpgList( int ) ) );

    m_epgTimer = new QTimer( this );
    connect( m_epgTimer, SIGNAL( timeout() ), this, SLOT( updateEpgListFromTimer() ) );

    connect( mainWindow->serverTimer(), SIGNAL( timeout() ), this, SLOT( updateTime() ) );
}


void WidgetOsdTv::setIndex( const QModelIndex &index )
{
    m_index = index;
    m_mapper->setCurrentModelIndex( index );
}


void WidgetOsdTv::updateOsdTv( const QModelIndex & topLeft )
{
    if ( !m_index.isValid() )
    {
        return;
    }

    if ( topLeft.row() != m_index.row() )
    {
        return;
    }

    m_mapper->setCurrentModelIndex( m_index );
}


void WidgetOsdTv::updateEpgList( int index )
{
    qDebug() << "WidgetOsdTv::updateEpgList with index" << index;

    if ( index != m_index.row() )
    {
        qDebug() << "WidgetOsdTv::updateEpgListFromTimer() was called, but index " << m_index.row() << " was expected";
        return;
    }

    QTableWidgetItem* item;

    //Trigger the epg update
    m_index.model()->data( m_index, ChannelListModel::ChannelEpgTriggerUpdate );
    ScheduleList scheduleList = m_mainWindow->channelList()->at( m_index.row() ).scheduleList;

    ui.tableWidget->setRowCount( scheduleList.size() );

    for ( int i = 0; i < scheduleList.size(); i++ )
    {
        item = new QTableWidgetItem( scheduleList[ i ].time.toString( "hh:mm" ) );
        ui.tableWidget->setItem( i, 0, item );
        item = new QTableWidgetItem( scheduleList[ i ].title );
        ui.tableWidget->setItem( i, 1, item );
    }

    if ( scheduleList.size() > 1 )
    {
        if( scheduleList[ 1 ].time.toTime_t() > m_mainWindow->serverTime().toTime_t() )
        {
            m_epgTimer->start( 1000 * ( scheduleList[ 1 ].time.toTime_t() - m_mainWindow->serverTime().toTime_t() ) );
            qDebug()<<"WidgetOsdTv::updateEpgListFromTimer(): new timer startet in " << scheduleList[ 1 ].time.toTime_t() - m_mainWindow->serverTime().toTime_t();
        }
        else
        {
            qDebug() << "WidgetOsdTv::updateEpgListFromTimer() was called, but epg time in the past";
            m_epgTimer->stop();
        }
    }
    else
    {
        qDebug() << "WidgetOsdTv::updateEpgListFromTimer() was called, but epg size too small: " << scheduleList.size();
        m_epgTimer->stop();
    }
}


void WidgetOsdTv::updateEpgListFromTimer()
{
    qDebug() << "WidgetOsdTv::updateEpgListFromTimer() was called";

// Without the following we may update the epg list, even that we don't have live-tv, but who really cares about this small roundtrip

//     if( !isVisible() )
//     {
//         m_epgTimer->stop();
//         return;
//     }
    updateEpgList( m_index.row() );
}


void WidgetOsdTv::updateTime()
{
    ui.time->setText( m_mainWindow->serverTime().toString( "hh:mm" ) );
}
